<script setup>
import "@/assets/css/dashboard-bootstrap.css";
import "@/assets/css/style.css";
import "bootstrap-icons/font/bootstrap-icons.css";
import { useUserStore } from "@/stores/user.js";
import { ref, computed, onMounted } from "vue"; // 修改此行，加入 ref, computed
import { useExamStore } from "@/stores/exam.js"; // 新增此行
import router from "@/router/index.js";
import { useForumStore } from "@/stores/forum.js";
const examStore = useExamStore(); // 新增此行
const historyAssessments = ref([]); // 新增此行，用于存储带有分数的历史考核
const uncompletedExams = ref([]);   // <-- 新增此行
const user = useUserStore();
const forumStore = useForumStore(); // 新增此行
user.getMyCourse();
onMounted(() => {
  // 调用 examStore 的 action 获取当前学生的所有考核信息
  examStore.fetchCurrentUserExams((data) => {
    if (data && data.completeExam) {
      // 与上一个页面逻辑相同，获取已完成考核的答卷详情
      fetchSubmissionsForCompletedExams(data.completeExam);
    }
    if (data.unCompleteExam) {
      uncompletedExams.value = data.unCompleteExam;
    }
  });
  forumStore.fetchCurrentUserPosts({ pageSize: -1 }); // pageSize: -1 表示获取全部，我们只需要 total
  forumStore.fetchCurrentUserReplies({ pageSize: -1 });
});
const timelineAssessments = computed(() => {
  // 1. 合并已完成和未完成的考核，并为已完成的考核添加 isCompleted 标记
  const completed = (historyAssessments.value || []).map(item => ({ ...item, isCompleted: true }));
  const uncompleted = (uncompletedExams.value || []).map(item => ({ ...item, isCompleted: false }));

  const allAssessments = [...completed, ...uncompleted];

  // 2. 筛选掉状态为 'draft' 或 'ended' 的考核
  const filtered = allAssessments.filter(item => {
    const status = item.exam.status;
    return status !== 'draft' && status !== 'ended';
  });

  // 3. 按开始时间升序排序
  return filtered.sort((a, b) => new Date(a.exam.startTime) - new Date(b.exam.startTime));
});
const formatDate = (dateString) => {
  if (!dateString) return "未指定";
  const date = new Date(dateString);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const goToCourseDetail = (courseId) => {
  router.push(`/student/course-detail/${courseId}`);
};
const getExamStatusInfo = (exam, isCompleted) => {
  if (isCompleted) {
    return { text: '已完成', type: 'success' };
  }

  const now = new Date();
  const startTime = new Date(exam.startTime);

  if (now < startTime) {
    return { text: '即将开始', type: 'warning' };
  }
  return { text: '进行中', type: 'danger' };
};
const fetchSubmissionsForCompletedExams = async (completedExams) => {
  if (!user.user?.id) return;

  const submissionPromises = completedExams.map(examData => {
    return new Promise((resolve) => {
      examStore.fetchSubmissions(
        { examId: examData.exam.id, studentId: user.user.id },
        (submissionData) => {
          // 将答卷信息附加到考核数据上
          resolve({ ...examData, submission: submissionData?.examSubmission });
        }
      );
    });
  });

  // 等待所有答卷信息获取完毕后，更新 historyAssessments
  historyAssessments.value = await Promise.all(submissionPromises);
};
const assessmentStatistics = computed(() => {
  // 筛选出有分数且已完成批改的答卷
  const gradedAssessments = historyAssessments.value.filter(
    item => item.submission &&
      item.submission.gradingStatus === 'completed' &&
      typeof item.submission.totalScore === 'number'
  );

  if (gradedAssessments.length === 0) {
    return { averageScore: '0.0', passRate: '0.0' };
  }

  // 计算总分
  const totalScoreSum = gradedAssessments.reduce(
    (sum, item) => sum + item.submission.totalScore, 0
  );
  // 计算通过数量
  const passedCount = gradedAssessments.filter(
    item => item.submission.totalScore >= 60
  ).length;

  // 返回计算结果
  return {
    averageScore: (totalScoreSum / gradedAssessments.length).toFixed(1),
    passRate: ((passedCount / gradedAssessments.length) * 100).toFixed(1)
  };
});
</script>

<template>
  <!-- 主要内容 -->
  <div class="container-fluid p-4">
    <!-- 欢迎信息 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="card-body p-4">
            <div class="d-flex align-items-center">
              <img src="/images/student.png" alt="用户头像" width="80" height="80"
    class="rounded-circle me-4" />
              <div>
                <h4 class="mb-1">欢迎回来，{{ user.user.name }}</h4>
                <!-- <p class="text-muted mb-0">上次登录: 2023年6月15日 14:30</p> -->
                <div class="mt-2">
                  <el-tag type="primary" class="m-2">
                    {{ user.user.stage==='intern'?'实习': '正式'}}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习进度和统计 -->
    <el-row :gutter="20" class="mb-4">
      <!-- <el-col :span="6">
        <el-card shadow="hover" class="h-100">
          <div class="card-body text-center">
            <h6 class="text-muted mb-2">总学习时长</h6>
            <h3 class="mb-0">42.5 小时</h3>
            <div class="mt-3">
              <el-tag type="success">本周 +3.5 小时</el-tag>
            </div>
          </div>
        </el-card>
      </el-col> -->
      <!-- <el-col :span="6">
        <el-card shadow="hover" class="h-100">
          <div class="card-body text-center">
            <h6 class="text-muted mb-2">已完成课程</h6>
            <h3 class="mb-0">8 / 12</h3>
            <el-progress
              :percentage="66"
              :stroke-width="8"
              class="mt-3"
            ></el-progress>
          </div>
        </el-card>
      </el-col> -->
      <el-col :span="6">
        <el-card shadow="hover" class="h-100 statistic-card theme-green" >
          <div class="card-body text-center">
            <h6 class="text-muted mb-2">平均分数</h6>
            <h3 class="mb-0">{{ assessmentStatistics.averageScore }}</h3>
            <div class="mt-3">
              <el-tag type="success">再接再厉</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="h-100 statistic-card theme-blue">
          <div class="card-body text-center">
            <h6 class="text-muted mb-2">考核通过率</h6>
            <h3 class="mb-0">{{ assessmentStatistics.passRate }}%</h3>
            <div class="mt-3">
              <el-tag type="info">优秀</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="h-100 statistic-card theme-orange">
          <div class="card-body text-center">
            <h6 class="text-muted mb-2">我的发帖</h6>
            <h3 class="mb-0">{{ forumStore.totalCurrentUserPosts }}</h3>
            <div class="mt-3">
              <el-tag type="warning">创作能手</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="h-100 statistic-card theme-purple">
          <div class="card-body text-center">
            <h6 class="text-muted mb-2">我的回复</h6>
            <h3 class="mb-0">{{ forumStore.totalCurrentUserReplies }}</h3>
            <div class="mt-3">
              <el-tag type="primary">热心讨论</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 进行中的课程 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <h5 class="mb-0">进行中的课程</h5>
          </template>
          <el-row :gutter="20">
            <el-col :span="12" v-for="course in user.myClass" class="course-item-col">
              <div class="d-flex">
                <img class="rounded me-3 course-cover-img" alt="课程缩略图" :src="course.coverUrl" />
                <div>
                  <h6 class="mb-1">{{ course.title }}</h6>
                  <p class="text-muted small mb-2">
                    导师: {{ course.createdBy }}
                  </p>
                  <!-- <el-progress :percentage="65" :stroke-width="6" class="mb-2"></el-progress> -->
                  <el-button type="primary" size="small" @click="goToCourseDetail(course.id)">继续学习
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
          <template #footer>
            <div class="text-center">
              <el-link type="primary" :underline="false" href="/student/learning-center">查看全部课程
              </el-link>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>

    <!-- 近期考核和培训计划 -->
    <el-row :gutter="20">
      <el-col :span="12" class="mb-4">
        <el-card shadow="hover" class="h-100">
          <template #header>
            <h5 class="mb-0">近期考核</h5>
          </template>
          <el-timeline v-if="timelineAssessments.length > 0">
            <el-timeline-item v-for="item in timelineAssessments" :key="item.exam.id"
              :timestamp="formatDate(item.exam.startTime)" placement="top">
              <h6 class="mb-1">{{ item.exam.title }}</h6>
              <p class="text-muted small mb-0">
                起止时间: {{ formatDate(item.exam.startTime) }} 至 {{ formatDate(item.exam.endTime) }}
              </p>
              <el-tag :type="getExamStatusInfo(item.exam, item.isCompleted).type">
                {{ getExamStatusInfo(item.exam, item.isCompleted).text }}
              </el-tag>
            </el-timeline-item>
          </el-timeline>
          <el-empty v-else description="暂无需要您关注的考核安排"></el-empty>
          <template #footer>
            <div class="text-center">
              <el-link type="primary" :underline="false" href="/student/student-assessment-plus">查看全部考核
              </el-link>
            </div>
          </template>
        </el-card>
      </el-col>
      <el-col :span="12" class="mb-4">
        <el-card shadow="hover" class="h-100">
          <template #header>
            <h5 class="mb-0">培训计划</h5>
          </template>
          <div class="mb-4">
            <h6>护理基础学习计划</h6>
            <p class="text-muted small mb-2">2025年7月1日 - 2025年7月14日</p>
            <el-progress :percentage="40" :stroke-width="8"></el-progress>
            <div class="d-flex justify-content-between mt-1">
              <small class="text-muted">已完成: 4/10 课程</small>
              <small class="text-muted">40%</small>
            </div>
          </div>
          <div>
            <h6>伤口护理实操计划</h6>
            <p class="text-muted small mb-2">2025年7月7日 - 2025年7月18日</p>
            <el-progress :percentage="10" :stroke-width="8"></el-progress>
            <div class="d-flex justify-content-between mt-1">
              <small class="text-muted">已完成: 1/8 课程</small>
              <small class="text-muted">10%</small>
            </div>
          </div>
          <template #footer>
            <div class="text-center">
              <el-link type="primary" :underline="false" href="/student/student-training-plan">查看培训计划详情
              </el-link>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<style scoped>
/* --- 统计卡片动态效果 --- */

.statistic-card {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 0.5rem;
  border: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.statistic-card :deep(.el-card__body) {
  position: relative;
  z-index: 2;
}

.statistic-card h3,
.statistic-card h6 {
  transition: color 0.4s ease-out 0.1s; /* 延迟文字变色，效果更佳 */
}

/* 关键：创建一个初始状态在左上角的、大小为0的伪元素 */
.statistic-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  background: var(--card-theme-gradient);
  /* 将伪元素旋转45度，并调整其变换原点到左上角 */
  transform-origin: top left;
  transform: rotate(45deg);
  transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1); /* 使用更平滑的动画曲线 */
  z-index: 1;
}

/* --- 悬浮效果 --- */
.statistic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
}
.statistic-card .card-body {
  position: relative;
  z-index: 2;
}

/* 悬浮时，将伪元素放大到足以覆盖整个卡片 */
.statistic-card:hover::before {
  /* 宽度和高度需要足够大以覆盖对角线 */
  width: 150%;
  height: 150%;
  
}

/* 悬浮时，改变文字颜色为白色 */
/* .statistic-card:hover h3,
.statistic-card:hover h6 {
  color: #fff !important;
} */

/* --- 定义不同的颜色主题 --- */
.theme-green {
  --card-theme-gradient: linear-gradient(to right, #28a745, #20c997);
}
.theme-blue {
  --card-theme-gradient: linear-gradient(to right, #4e73df, #36b9cc);
}
.theme-orange {
  --card-theme-gradient: linear-gradient(to right, #fd7e14, #ffc107);
}
.theme-purple {
  --card-theme-gradient: linear-gradient(to right, #6f42c1, #d63384);
}
.course-item-col {
  margin-bottom: 24px; /* 为每个课程项添加下边距 */
}

/* 最后一个课程项可能不需要下边距，以避免与页脚产生过大间距（可选优化）*/
.el-row .course-item-col:last-child {
    margin-bottom: 0;
}
/* 如果一行有两个，并且总数是奇数，需要额外处理 */
.el-row .course-item-col:nth-last-child(2):nth-child(odd) {
    margin-bottom: 0;
}
/* --- 页面其他通用样式 --- */

.text-muted {
  color: #6c757d !important;
}

.h-100 {
  height: 100%;
}

.text-center {
  text-align: center;
}

.el-card {
  border: none;
}
.course-cover-img {
  width: 120px; 
  height: 80px; 
  object-fit: cover; 
  background-color: #f8f9fa;
  flex-shrink: 0; 
}
</style>
